//路由鉴权
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import userStore from '@/store/modules/user'
import pinia from './store'
import { ElNotification } from 'element-plus'
nprogress.configure({ showSpinner: false })
const userStoreInfo = userStore(pinia)
//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  document.title = '当前位置 - ' + to.meta.title
  // to:你将要访问哪个路由
  // from:你从哪个路由而来
  // next:路由的放行函数
  // 返回 false 以取消导航
  // 获取token，去判断用户登录还是未登录
  const token = userStoreInfo.token
  const userInfoData = userStoreInfo.userInfo
  if (token) {
    //用户登录
    if (to.path == '/login') {
      //访问login
      next({ path: '/' })
    } else {
      //访问除了登录页：放行
      if (userInfoData.name) {
        next()
      } else {
        try {
          //获取用户信息
          await userStoreInfo.setUserInfo()
          next({ ...to })
        } catch (error) {
          //token过期
          //用户手动修改本地token
          ElNotification({
            type: 'error',
            title: 'token过期,请重新登录',
          })
          await userStoreInfo.userOutLogin()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    //用户未登录
    if (to.path == '/login') {
      //访问登录放行
      next()
    } else {
      //访问别的强制跳转到首页
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
  nprogress.start()
  next()
  // return false
})
//全局后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
